package com.superpet.weixin.api.login;

import com.jfinal.plugin.ehcache.CacheKit;
import com.superpet.common.kits.ConstantKit;
import com.superpet.common.kits.DateKit;
import com.superpet.common.model.Users;
import com.superpet.common.model.WxToken;
import com.superpet.common.vo.WxSessionVo;
import org.apache.commons.lang3.StringUtils;

import java.util.Date;

public class LoginService {

    public static final LoginService me = new LoginService();
    private String loginAccountCacheName = ConstantKit.LOGIN_ACCOUNT_CACHE;

    public void saveToken(WxSessionVo wxVo){
        WxToken token = new WxToken();
        token.setAccessToken(wxVo.getAccessToken());
        token.setOpenid(wxVo.getOpenid());
        token.setSessionKey(wxVo.getSession_key());
        token.setUpdateTime(DateKit.toTimeStr(new Date()));
        token.setUserId(wxVo.getUserId());
        token.save();
        //cache
        CacheKit.put(loginAccountCacheName,wxVo.getAccessToken(),wxVo);
    }

    public boolean hasLogin(String token){
        WxSessionVo wxVo = getWxTokenInfo(token);
        if(StringUtils.isNotBlank(wxVo.getOpenid())){
            return true;
        }else{
            return false;
        }
    }

    public WxSessionVo getWxTokenInfo(String token){
        WxSessionVo wxVo = new WxSessionVo();
        wxVo.setAccessToken(token);
        //读缓存
        WxSessionVo wxVoCache = CacheKit.get(loginAccountCacheName,token);
        //缓存有
        if(wxVoCache!=null && StringUtils.isNotBlank(wxVoCache.getOpenid())){
            wxVo.setOpenid(wxVoCache.getOpenid());
            wxVo.setSession_key(wxVoCache.getSession_key());
            wxVo.setUserId(wxVoCache.getUserId());
        }else{//缓存没有，查数据库
            WxToken wxToken = WxToken.dao.findFirst("select * from p_wx_token where accessToken=? limit 1", token);
            if(wxToken!=null){//数据库有
                wxVo.setOpenid(wxToken.getOpenid());
                wxVo.setSession_key(wxToken.getSessionKey());
                wxVo.setUserId(wxToken.getUserId());
                //Refresh Cache
                CacheKit.put(loginAccountCacheName,wxVo.getAccessToken(),wxVo);
            }
        }
        return wxVo;
    }

    public void clearSingleCache(String token){
        CacheKit.remove(loginAccountCacheName,token);
    }

    public void clearAllCache() {
        CacheKit.removeAll(loginAccountCacheName);
    }

}
